Repository navigation
Fix #15225 (FN arrayIndexOutOfBounds: sizeof(arr) unknown when the array dimension contains sizeof of a struct, variable or dereference) - #9037
Conversation
…ray dimension contains sizeof of a struct, variable or dereference) A dimension such as 10 + sizeof(struct S) was only marked known by SymbolDatabase::setArrayDimensionsUsingValueFlow(), which runs after all ValueFlow passes. Every reader inside ValueFlow saw it as unknown, so sizeof(arr), sizeof(arr) / sizeof(arr[0]) and sizeof of a struct that contains such an array got no value. valueFlowNumber() now sets the dimension when the token walk reaches the end of the array declaration, where constant folding has already given the dimension token a known value. Declarations precede uses, so the existing sizeof code then works unchanged, including for chained declarations such as char b[sizeof(a)]. The pass after ValueFlow stays for dimensions that only become known later. With more dimensions known, sizeof of an array function parameter would get the size of the array more often. It is a pointer, so sizeof now gives the pointer size and sizeof(p) / sizeof(p[0]) is no longer evaluated as the element count. The condition moves to Variable::isDecayedArrayArgument(), shared with CheckSizeof.
There was a problem hiding this comment.
Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota. Try requesting a review at a lower effort level.
An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.
dmcppcheck
left a comment
There was a problem hiding this comment.
AI review
The fix works for the cases in the ticket, and the full testrunner passes. I found one new problem, a small one: the new Variable::isDecayedArrayArgument() skips every std::array variable, including a parameter declared as an array of std::array. For void f(std::array<int, 4> a[2]), sizeof(a) still gets 16 instead of the pointer size, and sizeofwithsilentarraypointer gives no warning. This was already wrong on base, but the PR now says this helper is the rule for array parameters.
Some results change as expected from the pointer-size change. For example, void f(char a[4]) { memset(a, 0, sizeof(a)); } now also reports bufferAccessOutOfBounds. The old a[100] warning for void f4(char a[100]) { a[sizeof(a)] = 0; } is gone. Both are correct, since sizeof(a) is the pointer size, and sizeofwithsilentarraypointer still warns on those lines. Apart from the item above, I found no new problems.
Comments
| # | Comment | By | Where | Status |
|---|---|---|---|---|
| 1 | The std::array exclusion also covers arrays of std::array, e.g. std::array<int,4> a[2] |
AI review | lib/symboldatabase.cpp:2723 |
🆕 New (false negative) |
@JayToltTech, please fix, resolve or reply to the open and new comments: #1.
For #1 (false negative), it is enough to create a Trac ticket and link it here. It does not need to be fixed in this PR.
Testing
Build: I built cppcheck and testrunner in pr/ and cppcheck in base/. Both built without errors.
Tests: ./testrunner TestValueFlow TestBufferOverrun TestSizeof TestSymbolDatabase passed. The full ./testrunner -q also passed: 5420 tests, 0 failed.
My own tests: I wrote test files in scratch/ and ran base and PR on them with --enable=all.
What gets a value now that did not on base:
- Local arrays whose dimension contains
sizeof(struct S)orsizeof(var), including multi-dimensional ones. memset(a, 0, sizeof(a)+1).for (i <= sizeof(a)/sizeof(a[0])).- Chained declarations such as
char b[sizeof(t)], wheretis a struct whose member array has asizeofdimension. - Template functions like
char a[2 + sizeof(T)]. - Member arrays.
All of these now give the expected arrayIndexOutOfBounds or bufferAccessOutOfBounds. References to arrays, std::array by value and VLAs behave the same as on base.
What changed for array parameters:
void f(char a[4]) { char b[sizeof(a)]; b[8]=0; }now reportsb[8].for (i < sizeof(a)) a[i]withchar a[4]now reports index 7.void f(int a[2][3]) { int x[sizeof(a)]; }now givesx[8].
All of these are correct for 64-bit pointers.
The problem I found (also wrong on base, but the new helper keeps it):
#include <array>
void f1(std::array<int, 4> a[2]) { int x[sizeof(a)]; x[8] = 0; x[32] = 0; }
void g(std::array<int, 4> a[2]) { int x = sizeof(a); }pr/cppcheck --debug --verbose t4.cpp shows sizeof always 16 for g. It should be 8, the pointer size. Running pr/cppcheck -q t3.cpp reports only Array 'x[16]' accessed at index 32. It misses x[8], and there is no sizeofwithsilentarraypointer warning.
Side note: when the parameter is decayed, sizeof(p)/sizeof(p[0]) now gets no value at all, where base gave a wrong one. The reason is that the division branch in vf_common.cpp does not fall back to the %var% ) branch. This is conservative and matches how base already handles other divisions that do not match, so I am not reporting it.
Automated review of a985a2c by Claude. The pull request was built and tested locally.
|
|
||
| bool Variable::isDecayedArrayArgument() const | ||
| { | ||
| return isArray() && isArgument() && !isReference() && !(isStlType() && getTypeName() == "std::array"); |
There was a problem hiding this comment.
AI review
The std::array exclusion is meant for a std::array passed by value. It also matches a parameter declared as an array of std::array, and that parameter does decay to a pointer:
void g(std::array<int, 4> a[2]) { int x = sizeof(a); }--debug shows sizeof always 16, but the value should be the pointer size (8). In void f1(std::array<int, 4> a[2]) { int x[sizeof(a)]; x[8] = 0; } the x[8] access is missed, and sizeofwithsilentarraypointer does not warn.
The condition came over from CheckSizeof unchanged, but this helper is now what ValueFlow uses to decide what an array parameter is. One possible fix is to apply the std::array exception only when the parameter has no [...] of its own, for example when !Token::simpleMatch(nameToken()->next(), "[").
https://trac.cppcheck.net/ticket/15225
Replaces #9036, which I've closed. That one patched a single reader of the array dimension, and the review there found it gave a false positive for array parameters. Looking at why turned up the same cause in two more places, so this fixes the cause.
A dimension like
10 + sizeof(struct S),10 + sizeof(var)or10 + sizeof(*p)is only marked known bySymbolDatabase::setArrayDimensionsUsingValueFlow(), and that runs after all the ValueFlow passes. So everything inside ValueFlow sees the dimension as unknown, and none of these get a value:sizeof(arr)sizeof(arr) / sizeof(arr[0])sizeof(struct T)whereThas an array like that as a membervalueFlowNumber()now sets the dimension when the token walk gets to the end of the array declaration. Constant folding has already given the dimension token a known value by then, and declarations come before uses, so the existingsizeofcode works unchanged. Chained ones likechar b[sizeof(a)]work too. The pass after ValueFlow stays for dimensions that only become known later.Array parameters are the other half.
sizeofof an array function parameter is the size of a pointer, but it was being evaluated as the size of the array.void f(char p[10])gave 10 on main already, and knowing more dimensions would have spread that. It gives the pointer size now, andsizeof(p) / sizeof(p[0])isn't evaluated as the element count. The condition is inVariable::isDecayedArrayArgument(), whichCheckSizeofhad inline. References to arrays andstd::arrayby value keep their full size.Tests are in
TestValueFlow::valueFlowSizeof, plus a newTestBufferOverrun::array_index_78for thea[sizeof(a)]from the ticket. Both fail without thelib/change. testrunner passes on macOS arm64 andrunformatmakes no changes. I haven't run the selfcheck locally.The
const_castonDimensioninvalueflow.cppis the same onesetArrayDimensionsUsingValueFlow()already does. Change it as you see fit.